package com.geek.water.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.water.entity.Permission;
import com.geek.water.mapper.PermissionMapper;
import com.geek.water.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenmin
 * @desc 权限服务实现类
 * @date 2025/01/08
 */
@Service
@Slf4j
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getPermissionTree() {
        try {
            // 先尝试从permission表获取数据
            List<Permission> permissions = baseMapper.selectAllPermissions();

            if (permissions != null && !permissions.isEmpty()) {
                log.info("从permission表获取权限数据，数量: {}", permissions.size());
                return buildPermissionTreeFromPermissions(permissions);
            }

            // 如果permission表没有数据，尝试从menu表获取
            try {
                List<Object> menus = baseMapper.selectAllMenus();
                if (menus != null && !menus.isEmpty()) {
                    log.info("从menu表获取权限数据，数量: {}", menus.size());
                    return buildPermissionTreeFromMenus(menus);
                }
            } catch (Exception e) {
                log.warn("menu表查询失败，可能表不存在: {}", e.getMessage());
            }

            // 如果都没有数据，返回空列表
            log.warn("权限表和菜单表都没有数据，返回空权限树");
            return new ArrayList<>();

        } catch (Exception e) {
            log.error("获取权限树失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<Permission> getAllPermissions() {
        try {
            return baseMapper.selectAllPermissions();
        } catch (Exception e) {
            log.error("获取所有权限失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 从Permission实体构建权限树
     */
    private List<Map<String, Object>> buildPermissionTreeFromPermissions(List<Permission> permissions) {
        // 构建一个简单的权限树结构，避免重影
        Map<String, Object> rootNode = new HashMap<>();
        rootNode.put("id", 0);
        rootNode.put("name", "系统权限");
        rootNode.put("code", "SYSTEM_ROOT");
        rootNode.put("type", "module");
        rootNode.put("description", "系统所有权限");

        List<Map<String, Object>> children = permissions.stream().map(permission -> {
            Map<String, Object> node = new HashMap<>();
            node.put("id", permission.getId());
            node.put("name", permission.getName());
            node.put("code", permission.getName()); // permission表只有name字段
            node.put("type", "permission");
            node.put("description", "权限: " + permission.getName());
            node.put("children", new ArrayList<>()); // 权限节点没有子节点
            return node;
        }).collect(Collectors.toList());

        rootNode.put("children", children);

        List<Map<String, Object>> result = new ArrayList<>();
        result.add(rootNode);
        return result;
    }

    /**
     * 从Menu数据构建权限树
     */
    private List<Map<String, Object>> buildPermissionTreeFromMenus(List<Object> menus) {
        List<Map<String, Object>> tree = new ArrayList<>();
        Map<Integer, Map<String, Object>> nodeMap = new HashMap<>();

        // 先创建所有节点
        for (Object menuObj : menus) {
            if (menuObj instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> menu = (Map<String, Object>) menuObj;

                Map<String, Object> node = new HashMap<>();
                node.put("id", menu.get("id"));
                node.put("name", menu.get("name"));
                node.put("code", menu.get("path"));
                node.put("type", getMenuType((Integer) menu.get("level")));
                node.put("description", menu.get("name"));
                node.put("children", new ArrayList<Map<String, Object>>());

                nodeMap.put((Integer) menu.get("id"), node);
            }
        }

        // 构建树形结构
        for (Object menuObj : menus) {
            if (menuObj instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> menu = (Map<String, Object>) menuObj;

                Integer parentId = (Integer) menu.get("parentMenuId");
                Map<String, Object> currentNode = nodeMap.get((Integer) menu.get("id"));

                if (parentId == null || parentId == 0) {
                    // 根节点
                    tree.add(currentNode);
                } else {
                    // 子节点
                    Map<String, Object> parentNode = nodeMap.get(parentId);
                    if (parentNode != null) {
                        @SuppressWarnings("unchecked")
                        List<Map<String, Object>> children = (List<Map<String, Object>>) parentNode.get("children");
                        children.add(currentNode);
                    }
                }
            }
        }

        return tree;
    }

    /**
     * 根据菜单层级获取类型
     */
    private String getMenuType(Integer level) {
        if (level == null) return "menu";
        switch (level) {
            case 1: return "module";
            case 2: return "menu";
            default: return "button";
        }
    }
}
